#include "time_weather.h"
#include "wifi_dev.h"


WeatherClassStruct weatherClass;

#define HTTP_RECV_BUFFER_SIZE   300

static const char* weatherURL = "http://api.seniverse.com/v3/weather/now.json?key=Sa5FTVaE9Fkl-Vzom&location=zhengzhou&language=zh-Hans&unit=c";
static const char* timeURL = "time";

const char* TAG = "time_weather";
static char httpRecvBuffer[HTTP_RECV_BUFFER_SIZE] = {0};
esp_http_client_handle_t http_client;
TaskHandle_t HTTPHandle = NULL;


/**
  * @brief  心知天气json解析处理
  * @param  None
  * @retval None
  * @note   None
  */
void JSON_xin_zhi_tian_qi(char *buffer)
{
    cJSON* root = NULL;
    root = cJSON_Parse(buffer);

    cJSON* cjson_item =cJSON_GetObjectItem(root, "results");
    cJSON* cjson_results =  cJSON_GetArrayItem(cjson_item, 0);
    cJSON* cjson_now = cJSON_GetObjectItem(cjson_results, "now");
    cJSON* cjson_temperature = cJSON_GetObjectItem(cjson_now, "temperature");
    cJSON* cjson_code = cJSON_GetObjectItem(cjson_now, "code");

    memcpy(weatherClass.temperatureString, cjson_temperature->valuestring, strlen(cjson_temperature->valuestring));
    weatherClass.weatherCode = cjson_code->valueint;

    printf("HTTP: temperature: %s, weatherCode: %d\n", weatherClass.temperatureString, weatherClass.weatherCode);
}

void HTTP_run_task(void *pvParameters)
{

    while(1)
    {
        EventBits_t bits = xEventGroupGetBits(s_wifi_event_group);
        if(bits & WIFI_CONNECTED_BIT)
        {
            // 与目标主机创建连接，并且声明写入内容长度为0
            esp_err_t err = esp_http_client_open(http_client, 0);
            //如果连接失败
            if (err != ESP_OK) 
            {
                ESP_LOGE(TAG, "failed to open HTTP connection: %s", esp_err_to_name(err));
            }
            else 
            {
                //读取目标主机的返回内容的协议头
                int content_length = esp_http_client_fetch_headers(http_client);
                //如果协议头长度小于0，说明没有成功读取到
                if (content_length < 0) 
                {
                    ESP_LOGE(TAG, "HTTP client fetch headers failed");
                } // 如果成功读取到了协议头
                else 
                {
                    //读取目标主机通过http的响应内容
                    int readLength = esp_http_client_read_response(http_client, httpRecvBuffer, HTTP_RECV_BUFFER_SIZE);
                    if(readLength >= 0) 
                    {
                        //打印响应内容，包括响应状态，响应体长度及其内容
                        // ESP_LOGI(TAG, "HTTP GET Status = %d, content_length = %d",
                        // esp_http_client_get_status_code(http_client),				//获取响应状态信息
                        // esp_http_client_get_content_length(http_client));			//获取响应信息长度
                        // printf("data:%s\n", httpRecvBuffer);

                        JSON_xin_zhi_tian_qi(httpRecvBuffer);
                    } 
                    //如果不成功
                    else 
                    {
                        ESP_LOGE(TAG, "failed to read response");
                    }
                }
            }
            //关闭连接
            esp_http_client_close(http_client);
        }

        vTaskDelay(60000/portTICK_PERIOD_MS);
    }
}

void HTTP_init(void)
{
    esp_http_client_config_t config;
    memset(&config, 0, sizeof(config)); // 解决访问地址为NULL的问题
    config.url = weatherURL;
    memset(&http_client, 0, sizeof(http_client));
    //初始化结构体                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
    http_client = esp_http_client_init(&config);	//初始化http连接
    //设置发送请求
    esp_http_client_set_method(http_client, HTTP_METHOD_GET);
    ESP_LOGI(TAG, "HTTP init complate");
}

void HTTP_task_create(void)
{
    xTaskCreate(&HTTP_run_task, "HTTP_run_task", 8192, NULL, 0, &HTTPHandle);
}

void HTTP_task_delete(void)
{
    vTaskDelete(HTTPHandle);
}
